package JianZhiOffer;

/**
 * 输入一个整数数组，实现一个函数来调整该数组中数字的顺序，使得所有奇数位于数组的前半部分，所有偶数位于数组的后半部分。
 * */
public class Solution21 {

    /**
     * 双指针解法
     * */
    public int[] exchange1(int[] nums) {
        int i = 0, j = nums.length - 1, tmp;
        while(i < j) {
            while(i < j && (nums[i] & 1) == 1) i++;
            while(i < j && (nums[j] & 1) == 0) j--;
            tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
        }
        return nums;
    }

    /**
     * 快慢指针解法
     * */
    public static int[] exchange(int[] nums) {
        int slow = 0,fast = 0;
        while(fast<nums.length){
            if((nums[fast]&1)==1) swap(nums,slow++,fast);
            fast++;
        }
        return nums;
    }

    public static void swap(int[] nums,int a,int b){
        int temp = nums[a];
        nums[a] = nums[b];
        nums[b] =temp;
        return;
    }

    public static void main(String[] args) {
        int[] exch = exchange(new int[]{1, 4, 8, 6, 5, 4, 3, 2});
        for (int i = 0; i < exch.length; i++) {
            System.out.println(exch[i]);
        }

    }
}
